package top.dingwen.io.treasure.websocket.util;

import cn.hutool.core.collection.CollUtil;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.socket.*;
import top.dingwen.io.treasure.base.constant.SupWarsConstant;
import top.dingwen.io.treasure.base.util.spring.SpringUtils;
import top.dingwen.io.treasure.redis.core.IRedisCacheService;
import top.dingwen.io.treasure.websocket.constant.WebSocketConstant;
import top.dingwen.io.treasure.websocket.core.holder.WebSocketSessionHolder;
import top.dingwen.io.treasure.websocket.core.WebSocketMsg;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.Consumer;

/**
 * 工具类
 *
 * @author dingwen
 * @since 2024/10/16
 */
@Slf4j
@NoArgsConstructor(access = AccessLevel.PRIVATE)
@SuppressWarnings(SupWarsConstant.UNUSED)
public class WebSocketUtils {

    /**
     * 向指定的WebSocket会话发送消息
     *
     * @param sessionKey 要发送消息的用户id
     * @param message    要发送的消息内容
     */
    public static void sendMessage(String sessionKey, String message) {
        WebSocketSession session = WebSocketSessionHolder.getSessions(sessionKey);
        sendMessage(session, message);
    }


    /**
     * 所有WebSocket会话发送消息
     *
     * @param message 要发送的消息内容
     */
    public static void sendMessages(String message) {
        Set<String> sessionKeysAll = WebSocketSessionHolder.getSessionKeysAll();
        if (CollUtil.isEmpty(sessionKeysAll)) {
            return;
        }
        for (String session : sessionKeysAll) {
            sendMessage(session, message);
        }
    }

    /**
     * 订阅WebSocket消息主题，并提供一个消费者函数来处理接收到的消息
     *
     * @param consumer 处理WebSocket消息的消费者函数
     */
    public static void subscribeMessage(Consumer<WebSocketMsg> consumer) {
        IRedisCacheService redisCacheService = SpringUtils.safeGetBean("redissonServiceImpl",
                IRedisCacheService.class);
        if (Objects.isNull(redisCacheService)) {
            return;
        }
        redisCacheService.subscribe(WebSocketConstant.WEB_SOCKET_TOPIC, WebSocketMsg.class, consumer);
    }

    /**
     * 发布WebSocket订阅消息
     *
     * @param webSocketMsg 要发布的WebSocket消息对象
     */
    public static void publishMessage(WebSocketMsg webSocketMsg) {
        List<String> unsentSessionKeys = new ArrayList<>();
        // 当前服务内session,直接发送消息
        for (String sessionKey : webSocketMsg.getSessionKeys()) {
            if (WebSocketSessionHolder.existSession(sessionKey)) {
                WebSocketUtils.sendMessage(sessionKey, webSocketMsg.getMessage());
                // 更新存活时间
                WebSocketSessionHolder.updateActiveTime(sessionKey);
                continue;
            }
            unsentSessionKeys.add(sessionKey);
        }
        // 不在当前服务内session,发布订阅消息
        if (CollUtil.isNotEmpty(unsentSessionKeys)) {
            WebSocketMsg broadcastMessage = WebSocketMsg
                    .builder()
                    .message(webSocketMsg.getMessage())
                    .sessionKeys(unsentSessionKeys)
                    .build();
            IRedisCacheService redisCacheService = SpringUtils.safeGetBean("redissonServiceImpl",
                    IRedisCacheService.class);
            if (Objects.isNull(redisCacheService)) {
                return;
            }
            redisCacheService.publish(WebSocketConstant.WEB_SOCKET_TOPIC, broadcastMessage, consumer ->
                    log.info("{},{},WebSocket发送主题订阅消息topic:[{}] session keys:[{}] message:[{}]",
                            WebSocketConstant.WS_L_O_S,
                            WebSocketConstant.WS_L_U,
                            WebSocketConstant.WEB_SOCKET_TOPIC, unsentSessionKeys,
                            webSocketMsg.getMessage()));
        }
    }

    /**
     * 向所有的WebSocket会话发布订阅的消息(群发)
     *
     * @param message 要发布的消息内容
     */
    public static void publishAll(String message) {
        WebSocketMsg broadcastMessage = WebSocketMsg
                .builder()
                .message(message)
                .build();
        IRedisCacheService redisCacheService = SpringUtils.safeGetBean("redissonServiceImpl",
                IRedisCacheService.class);
        if (Objects.isNull(redisCacheService)) {
            return;
        }
        redisCacheService.publish(WebSocketConstant.WEB_SOCKET_TOPIC, broadcastMessage, consumer ->
                log.info("{},{},WebSocket发送主题订阅消息topic:{} message:{}",
                        WebSocketConstant.WS_L_O_S,
                        WebSocketConstant.WS_L_U,
                        WebSocketConstant.WEB_SOCKET_TOPIC, message
                ));
    }

    /**
     * 向指定的WebSocket会话发送Pong消息
     *
     * @param session 要发送Pong消息的WebSocket会话
     */
    public static void sendPongMessage(WebSocketSession session) {
        sendMessage(session, WebSocketConstant.PONG);
    }

    /**
     * 向指定的WebSocket会话发送Ping消息
     *
     * @param session 要发送Ping消息的WebSocket会话
     */
    public static void sendPingMessage(WebSocketSession session) {
        sendMessage(session, new PingMessage());
    }

    /**
     * 向指定的WebSocket会话发送文本消息
     *
     * @param session WebSocket会话
     * @param message 要发送的文本消息内容
     */
    public static void sendMessage(WebSocketSession session, String message) {
        sendMessage(session, new TextMessage(message));
    }

    /**
     * 向指定的WebSocket会话发送WebSocket消息对象
     *
     * @param session WebSocket会话
     * @param message 要发送的WebSocket消息对象
     */
    private synchronized static void sendMessage(WebSocketSession session, WebSocketMessage<?> message) {
        if (Objects.isNull(session)|| !session.isOpen()) {
            log.warn("{},{},[send] session会话已经关闭", WebSocketConstant.WS_L_O_S, WebSocketConstant.WS_L_U);
        } else {
            try {
                session.sendMessage(message);
            } catch (IOException e) {
                log.error("{},{},[send] session[{}] 发送消息[{}] 异常",
                        WebSocketConstant.WS_L_O_S,
                        WebSocketConstant.WS_L_U,
                        session, message, e);
            }
        }
    }
}
